/*
 * Licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.submarine.transport;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.submarine.common.URL;
import org.submarine.exchange.adapter.ExchangeAdapter;

/**
 * @file org.submarine.transport.EndpointFactory.java
 *
 * EndpointFactory
 * 
 * @author gaojian
 * @created 2013-8-28 上午10:08:31
 * @version 0.0.1
 * @since 0.0.1
 * 
 */
public abstract class EndpointFactory {
	
	private static final Map<URL, Endpoint> clientMap = new ConcurrentHashMap<URL, Endpoint>();
	
	private static final Map<String, Endpoint> serverMap = new ConcurrentHashMap<String, Endpoint>();
	
	/**
	 * 
	 * 创建Client
	 *
	 * @author gaojian
	 * @created 2013年8月25日 上午12:55:58
	 *
	 * @param url
	 * @return
	 */
	public Endpoint getClient(URL url, ExchangeAdapter exchangeAdapter) {
		if (!clientMap.containsKey(url)) {
			clientMap.put(url, doCreateClient(exchangeAdapter));
		}
		return clientMap.get(url);
	}
	
	/**
	 * 
	 * 具体实现类执行创建Client
	 *
	 * @author gaojian
	 * @created 2013年8月25日 上午12:55:46
	 *
	 * @return
	 */
	abstract protected Endpoint doCreateClient(ExchangeAdapter exchangeAdapter);
	
	/**
	 * 
	 * 创建Server
	 *
	 * @author gaojian
	 * @created 2013年8月25日 下午4:29:49
	 *
	 * @param url
	 * @param endpoint
	 * @return
	 */
	public Endpoint getServer(URL url, ExchangeAdapter exchangeAdapter) {
		if (!serverMap.containsKey(url.getAddress())) {
			serverMap.put(url.getAddress(), doCreateServer(exchangeAdapter));
		}
		return serverMap.get(url.getAddress());
	}
	
	/**
	 * 
	 * 具体实现类执行创建Server
	 *
	 * @author gaojian
	 * @created 2013年8月25日 下午4:29:14
	 *
	 * @return
	 */
	abstract protected Endpoint doCreateServer(ExchangeAdapter exchangeAdapter);

}
